package com.tv.cms.base.service;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.Country;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @project tvcms
 * @description
 * @date 2023/7/19 02:12:53
 */
@Service
public class GeoIPService {
    private DatabaseReader dbReader;

    public GeoIPService() throws IOException {
        Resource resource = new ClassPathResource("GeoLite2-Country.mmdb");
        InputStream inputStream = resource.getInputStream();
        dbReader = new DatabaseReader.Builder(inputStream).build();
    }

    /**
     * 根据ip查询国家
     * @param ipAddress
     * @return
     * @throws IOException
     */
    public String getCountryByIpAddress(String ipAddress) throws IOException {
        InetAddress ip = InetAddress.getByName(ipAddress);
        CityResponse response;
        try {
            response = dbReader.city(ip);
        } catch (GeoIp2Exception e) {
            throw new RuntimeException(e);
        }
        return response.getCountry().getName();
    }

    /**
     * 判断是不是国内ip
     * @param ipAddress
     * @return
     */
    public boolean isChinaMainland(String ipAddress){
        InetAddress ip;
        try {
            ip = InetAddress.getByName(ipAddress);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        CountryResponse response;
        try {
            response = dbReader.country(ip);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (GeoIp2Exception e) {
            throw new RuntimeException(e);
        }
        String countryIsoCode = response.getCountry().getIsoCode();
        return countryIsoCode.equals("CN");
    }
}
